﻿using FastExecutor.Base.Util;
using FastExecutor.Base.Design;
using FastExecutor.Base.Model;
using FastExecutor.ORG.DB;
using FastExecutor.ORG.Entity;
using FastORM.Applicaiton;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using FastIOC.Annotation;
using System.Web;
using System.Xml;
using System.IO;
using FastUtil.Base;

namespace FastExecutor.ORG.Controller
{
    [RouteArea("Frame")]
    [RoutePrefix("Table")]
    public class TableController : FastTemplateController<Frame_Table>
    {
        [AutoWired]
        public DB_Table @DB_Table;
        [AutoWired]
        private DB_Column @DB_Column;
        [AutoWired]
        private TemplateUtil @TemplateUtil;

        [Route("List")]
        public ActionResult List()
        {
            return View("~/Views/Frame/DMP/Table_List.cshtml");
        }
        [Route("Add")]
        public ActionResult Add()
        {
            return View("~/Views/Frame/DMP/Table_Add.cshtml");
        }
        [Route("Edit")]
        public ActionResult Edit()
        {
            return View("~/Views/Frame/DMP/Table_Edit.cshtml");
        }

        [Route("NameSpaceEdit")]
        public ActionResult NameSpaceEdit()
        {
            return View("~/Views/Frame/DMP/Table_NameSpaceSetting..cshtml");
        }

        [HttpPost, Route("FindList")]
        public override ActionResult FindList()
        {
            JObject Params = GetParams();
            string TableName = Convert.ToString(Params["TableName"]);
            string SQLTableName = Convert.ToString(Params["SQLTableName"]);
            string GroupGuid = Convert.ToString(Params["GroupGuid"]);
            if (!string.IsNullOrEmpty(TableName))
            {
                ListWhereText += string.Format(" and TableName like '%{0}%'", TableName);
            }
            if (!string.IsNullOrEmpty(SQLTableName))
            {
                ListWhereText += string.Format(" and SQLTableName like '%{0}%'", SQLTableName);
            }
            if (!string.IsNullOrEmpty(GroupGuid))
            {
                ListWhereText += string.Format(" and GroupGuid='{0}'", GroupGuid);
            }
            return base.FindList();
        }

        [HttpPost, Route("FindDetail")]
        public override ActionResult FindDetail()
        {
            return base.FindDetail();
        }

        [HttpPost, Route("OperateAdd")]
        public override ActionResult OperateAdd(Frame_Table Entity)
        {
            ReturnValue result = new ReturnValue();
            DBRow row = new DBRow("Frame_Table", "SQLTableName", Entity.SQLTableName);
            if (row.IsExist())
            {
                result.Add("code", -100);
                result.Add("msg", "已存在相同名称的表！");
                return result;
            }
            else
            {
                return base.OperateAdd(Entity);
            }

        }

        [HttpPost, Route("OperateUpdate")]
        public override ActionResult OperateUpdate()
        {
            return base.OperateUpdate();
        }

        [HttpPost, Route("OperateBatchDelete")]
        public override ActionResult OperateBatchDelete()
        {
            return base.OperateBatchDelete();
        }


        [HttpGet, Route("ExportXML")]
        public ContentResult ExportXML()
        {
            ContentResult result = new ContentResult();
            JObject Params = GetParams();
            string KeyGuidList = Convert.ToString(Params.GetValue("KeyGuidList"));
            result.Content = @DB_Table.ExportXML(KeyGuidList.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList());
            result.ContentEncoding = Encoding.UTF8;
            result.ContentType = "text/xml";
            return result;
        }

        [HttpPost, Route("ImportXML")]
        public ActionResult ImportXML()
        {
            ReturnValue result = new ReturnValue();
            HttpFileCollectionBase FileList = Request.Files;
            if (FileList.Count > 0)
            {
                HttpPostedFileBase File = FileList[0];
                StreamReader Reader = new StreamReader(File.InputStream, System.Text.Encoding.UTF8);
                string StramReader = Reader.ReadToEnd().Trim();
                XmlDocument Doc = new XmlDocument();
                Doc.LoadXml(StramReader);
                Frame_Table Table = null;
                List<Frame_TableStruct> ColumnList = new List<Frame_TableStruct>();
                XmlNodeList TableInfoList = Doc.SelectNodes("/TableInfos/TableInfo");
                foreach (XmlNode Node in TableInfoList)
                {
                    XmlNode TableDetail = Node.SelectSingleNode("TableDetail");
                    Table = ConvertUtil.ConvertXMLNode2Entity<Frame_Table>(TableDetail);
                    XmlNodeList TableColumns = Node.SelectNodes("Columns/Column");
                    foreach (XmlNode ColumnNode in TableColumns)
                    {
                        ColumnList.Add(ConvertUtil.ConvertXMLNode2Entity<Frame_TableStruct>(ColumnNode));
                    }
                }
                string ExceptionStr = string.Empty;
                @DBUtil.ExecuteTransition_SDB(delegate()
                {
                    DB_Fast.Insert(Table);
                    foreach (Frame_TableStruct Column in ColumnList)
                    {
                        if (Column.IsSys == 0)
                        {
                            @DB_Column.Insert(Column);
                        }

                    }
                }, out ExceptionStr);
                if (!string.IsNullOrEmpty(ExceptionStr))
                {
                    result.Add("code", -1);
                    result.Add("msg", ExceptionStr);
                }
            }
            return result;
        }

        [HttpPost, Route("GeneratCodeFile")]
        public ActionResult GeneratCodeFile()
        {
            ReturnValue result = new ReturnValue();
            JObject Params = GetParams();
            string KeyGuidList = Convert.ToString(Params["KeyGuidList"]);
            string NameSpace = Convert.ToString(Params["NameSpace"]);
            string Prefix = Convert.ToString(Params["Prefix"]);
            string FileID = @DB_Table.CreateCodeFile(Prefix,NameSpace, KeyGuidList.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList());
            result.Add("FileID", FileID);
            return result;
        }

        [HttpGet, Route("ReadCodeFile")]
        public ActionResult ReadCodeFile()
        {
            ReturnValue result = new ReturnValue();
            JObject Params = GetParams();
            string FileID = Convert.ToString(Params["FileID"]);
            string FielPath = @TemplateUtil.CodeTempPath + "/" + FileID + ".zip";
            Response.Redirect(CommonUtil.GetRootPath() + FielPath);
            return result;
        }


    }
}
